package cn.edu.whu.forecast.util;

import cn.edu.whu.forecast.entity.mysql.UserInfo;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    public static long timeout = 1000*60*60*24*7L;
    public static String signature = "quanzhou";

    public static String createToken(UserInfo userInfo){
        JwtBuilder jwtBuilder = Jwts.builder();

        String token = jwtBuilder
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .claim("username",userInfo.getUsername())
                .claim("password",userInfo.getPassword())
                .claim("role",userInfo.getRole().toString())
                .setSubject("user")
                .setExpiration(new Date(System.currentTimeMillis()+timeout))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();

        return token;
    }

    public static boolean checkToken(String token){
        if(token==null) return false;
        try{
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        }catch (Exception e){
            return  false;
        }
        return true;
    }
}
